// 高性能图标管理器
export class HighPerformanceBillboardManager {
    constructor(viewer) {
        this.viewer = viewer;
        this.billboardCollection = null;
        this.labelCollection = null;
        this.backgroundLabelCollection = null;
        this.iconCount = 0;
        this.billboardData = new Map();
        this.showIcons = true;
        this.showLabels = true;
        this.currentTextColor = Cesium.Color.WHITE;
        this.currentBackgroundColor = Cesium.Color.BLACK;

        // 放置模式相关属性
        this.placementMode = false;
        this.tempBillboard = null;
        this.tempBackgroundLabel = null;
        this.tempForegroundLabel = null;
        this.mouseMoveHandler = null;
        this.leftClickHandler = null;
        this.rightClickHandler = null;
        this.placementCallback = null;

        // 设置拾取事件
        this.setupPicking();
    }

    // 批量添加图标和广告牌
    async addBillboardsBatch(billboardsData) {
        const startTime = performance.now();

        // 清除现有图标
        this.clearBillboards();

        // 创建图标集合
        this.billboardCollection = new Cesium.BillboardCollection({
            scene: this.viewer.scene
        });

        // 创建文字标签集合（前景文字）
        this.labelCollection = new Cesium.LabelCollection({
            scene: this.viewer.scene
        });

        // 创建背景文字集合（模拟背景效果）
        this.backgroundLabelCollection = new Cesium.LabelCollection({
            scene: this.viewer.scene
        });

        // 添加到场景
        this.viewer.scene.primitives.add(this.billboardCollection);
        this.viewer.scene.primitives.add(this.backgroundLabelCollection);
        this.viewer.scene.primitives.add(this.labelCollection);

        // 批量创建图标和标签
        billboardsData.forEach((data, index) => {
            this.createBillboardWithLabel(data, index);
        });

        this.iconCount = billboardsData.length;

        const endTime = performance.now();
        return {
            time: (endTime - startTime).toFixed(2),
            count: billboardsData.length
        };
    }

    createBillboardWithLabel(data, index) {
        const position = Cesium.Cartesian3.fromDegrees(
            data.longitude,
            data.latitude,
            data.height || 0
        );

        const id = `billboard-${index}`;

        // 创建图标
        const billboard = this.billboardCollection.add({
            position: position,
            image: this.createSVGDataUrl(data.color, data.iconText),
            scale: 0.5,
            width: 32,
            height: 32,
            id: id,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(0, 0),
            show: this.showIcons
        });

        // 创建背景文字（模拟背景效果）
        const backgroundLabel = this.backgroundLabelCollection.add({
            position: position,
            text: data.name,
            font: 'bold 14px Arial',
            fillColor: this.currentBackgroundColor,
            outlineColor: this.currentBackgroundColor,
            outlineWidth: 8, // 粗边框模拟背景
            pixelOffset: new Cesium.Cartesian2(0, -35),
            verticalOrigin: Cesium.VerticalOrigin.TOP,
            heightReference: Cesium.HeightReference.NONE,
            show: this.showLabels,
            id: id + '-bg',
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            scale: 1.0
        });

        // 创建前景文字
        const foregroundLabel = this.labelCollection.add({
            position: position,
            text: data.name,
            font: 'bold 12px Arial',
            fillColor: this.currentTextColor,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 1,
            pixelOffset: new Cesium.Cartesian2(0, -35),
            verticalOrigin: Cesium.VerticalOrigin.TOP,
            heightReference: Cesium.HeightReference.NONE,
            show: this.showLabels,
            id: id + '-fg',
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            scale: 0.9
        });

        // 存储图标数据
        this.billboardData.set(id, {
            data: data,
            billboard: billboard,
            backgroundLabel: backgroundLabel,
            foregroundLabel: foregroundLabel
        });
    }

    createSVGDataUrl(color, text) {
        const svg = `
                    <svg width="32" height="32" xmlns="http://www.w3.org/2000/svg">
                        <circle cx="16" cy="16" r="14" fill="${color}" stroke="white" stroke-width="2"/>
                        <text x="16" y="20" text-anchor="middle" fill="white" font-size="12" font-weight="bold">${text || '!'}</text>
                    </svg>
                `;
        return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
    }

    // 更新所有文字广告牌的颜色
    updateLabelColors(backgroundColor, textColor = Cesium.Color.WHITE) {
        this.currentBackgroundColor = backgroundColor;
        this.currentTextColor = textColor;

        if (this.backgroundLabelCollection && this.labelCollection) {
            // 更新背景文字
            this.backgroundLabelCollection.forEach(label => {
                label.fillColor = backgroundColor;
                label.outlineColor = backgroundColor;
            });

            // 更新前景文字
            this.labelCollection.forEach(label => {
                label.fillColor = textColor;
            });
        }
    }

    // 添加单个图标和广告牌
    addSingleBillboard(data) {
        if (!this.billboardCollection) {
            this.billboardCollection = new Cesium.BillboardCollection({
                scene: this.viewer.scene
            });
            this.viewer.scene.primitives.add(this.billboardCollection);
        }

        if (!this.labelCollection) {
            this.labelCollection = new Cesium.LabelCollection({
                scene: this.viewer.scene
            });
            this.viewer.scene.primitives.add(this.labelCollection);
        }

        if (!this.backgroundLabelCollection) {
            this.backgroundLabelCollection = new Cesium.LabelCollection({
                scene: this.viewer.scene
            });
            this.viewer.scene.primitives.add(this.backgroundLabelCollection);
        }

        this.createBillboardWithLabel(data, this.iconCount);
        this.iconCount++;
    }

    // 设置拾取功能
    setupPicking() {
        const handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);

        handler.setInputAction((event) => {
            const picked = this.viewer.scene.pick(event.position);
            if (Cesium.defined(picked) && picked.id) {
                const billboardId = picked.id;
                const item = this.billboardData.get(billboardId);
                if (item) {
                    this.showPickedInfo(item.data);
                }
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }

    showPickedInfo(data) {
        const infoBox = document.getElementById('infoBox');
        const infoContent = document.getElementById('infoContent');

        infoContent.innerHTML = `
                    <div><strong>名称:</strong> ${data.name}</div>
                    <div><strong>经度:</strong> ${data.longitude.toFixed(4)}</div>
                    <div><strong>纬度:</strong> ${data.latitude.toFixed(4)}</div>
                    <div><strong>高度:</strong> ${(data.height || 0).toFixed(0)} 米</div>
                    <div style="display: flex; align-items: center; margin-top: 8px;">
                        <strong>颜色:</strong> 
                        <div style="width: 16px; height: 16px; background: ${data.color}; margin-left: 8px; border-radius: 3px;"></div>
                    </div>
                    <div><strong>图标文字:</strong> ${data.iconText}</div>
                `;

        infoBox.style.display = 'block';
    }

    // 切换图标显示状态
    toggleIconsVisibility(show) {
        this.showIcons = show;
        if (this.billboardCollection) {
            this.billboardCollection.forEach(billboard => {
                billboard.show = show;
            });
        }
    }

    // 切换广告牌显示状态
    toggleLabelsVisibility(show) {
        this.showLabels = show;
        if (this.labelCollection) {
            this.labelCollection.forEach(label => {
                label.show = show;
            });
        }
        if (this.backgroundLabelCollection) {
            this.backgroundLabelCollection.forEach(label => {
                label.show = show;
            });
        }
    }

    // 清除所有图标和广告牌
    clearBillboards() {
        if (this.billboardCollection) {
            this.viewer.scene.primitives.remove(this.billboardCollection);
            this.billboardCollection = null;
        }
        if (this.labelCollection) {
            this.viewer.scene.primitives.remove(this.labelCollection);
            this.labelCollection = null;
        }
        if (this.backgroundLabelCollection) {
            this.viewer.scene.primitives.remove(this.backgroundLabelCollection);
            this.backgroundLabelCollection = null;
        }
        this.billboardData.clear();
        this.iconCount = 0;

        // 隐藏信息框
        // document.getElementById('infoBox').style.display = 'none';
    }

    // 获取图标数量
    getIconCount() {
        return this.iconCount;
    }

    // ============ 新增的放置模式功能 ============

    /**
     * 开始放置模式
     * @param {Object} options 放置选项
     * @param {Function} callback 放置完成后的回调函数
     */
    startPlacementMode(options = {}, callback = null) {
        if (this.placementMode) {
            console.warn('放置模式已激活');
            return;
        }

        this.placementMode = true;
        this.placementCallback = callback;

        // 创建临时图标
        this.createTempBillboard(options);

        // 设置鼠标移动事件 - 图标跟随鼠标
        this.mouseMoveHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.mouseMoveHandler.setInputAction((event) => {
            const position = this.getPositionFromMouse(event.endPosition);
            if (position) {
                this.updateTempBillboardPosition(position);
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        // 设置左键点击事件 - 放置图标
        this.leftClickHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.leftClickHandler.setInputAction((event) => {
            const position = this.getPositionFromMouse(event.position);
            if (position) {
                this.placeBillboard(position, options);
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        // 设置右键点击事件 - 取消放置
        this.rightClickHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.rightClickHandler.setInputAction(() => {
            this.cancelPlacementMode();
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

        console.log('放置模式已激活: 左键放置图标，右键取消');
    }

    /**
     * 停止放置模式
     */
    stopPlacementMode() {
        if (!this.placementMode) return;

        this.placementMode = false;

        // 移除事件处理器
        if (this.mouseMoveHandler) {
            this.mouseMoveHandler.destroy();
            this.mouseMoveHandler = null;
        }
        if (this.leftClickHandler) {
            this.leftClickHandler.destroy();
            this.leftClickHandler = null;
        }
        if (this.rightClickHandler) {
            this.rightClickHandler.destroy();
            this.rightClickHandler = null;
        }

        // 移除临时图标
        this.removeTempBillboard();

        console.log('放置模式已停止');
    }

    /**
     * 取消放置模式
     */
    cancelPlacementMode() {
        this.stopPlacementMode();
        if (this.placementCallback) {
            this.placementCallback(null, 'cancelled');
        }
    }

    /**
     * 创建临时图标（跟随鼠标）
     */
    createTempBillboard(options = {}) {
        // 确保集合存在
        if (!this.billboardCollection) {
            this.billboardCollection = new Cesium.BillboardCollection({
                scene: this.viewer.scene
            });
            this.viewer.scene.primitives.add(this.billboardCollection);
        }

        if (!this.labelCollection) {
            this.labelCollection = new Cesium.LabelCollection({
                scene: this.viewer.scene
            });
            this.viewer.scene.primitives.add(this.labelCollection);
        }

        if (!this.backgroundLabelCollection) {
            this.backgroundLabelCollection = new Cesium.LabelCollection({
                scene: this.viewer.scene
            });
            this.viewer.scene.primitives.add(this.backgroundLabelCollection);
        }

        // 创建临时图标（半透明显示）
        this.tempBillboard = this.billboardCollection.add({
            image: this.createSVGDataUrl(options.color || '#FF5722', options.iconText || '?'),
            scale: 0.5,
            width: 32,
            height: 32,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(0, 0),
            show: this.showIcons,
            color: Cesium.Color.WHITE.withAlpha(0.7) // 半透明
        });

        // 创建临时标签
        const labelText = options.name || '新地点';
        this.tempBackgroundLabel = this.backgroundLabelCollection.add({
            text: labelText,
            font: 'bold 14px Arial',
            fillColor: this.currentBackgroundColor.withAlpha(0.7),
            outlineColor: this.currentBackgroundColor.withAlpha(0.7),
            outlineWidth: 8,
            pixelOffset: new Cesium.Cartesian2(0, -35),
            verticalOrigin: Cesium.VerticalOrigin.TOP,
            heightReference: Cesium.HeightReference.NONE,
            show: this.showLabels,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            scale: 1.0
        });

        this.tempForegroundLabel = this.labelCollection.add({
            text: labelText,
            font: 'bold 12px Arial',
            fillColor: this.currentTextColor.withAlpha(0.7),
            outlineColor: Cesium.Color.BLACK.withAlpha(0.7),
            outlineWidth: 1,
            pixelOffset: new Cesium.Cartesian2(0, -35),
            verticalOrigin: Cesium.VerticalOrigin.TOP,
            heightReference: Cesium.HeightReference.NONE,
            show: this.showLabels,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            scale: 0.9
        });
    }

    /**
     * 移除临时图标
     */
    removeTempBillboard() {
        if (this.tempBillboard && this.billboardCollection) {
            this.billboardCollection.remove(this.tempBillboard);
            this.tempBillboard = null;
        }
        if (this.tempBackgroundLabel && this.backgroundLabelCollection) {
            this.backgroundLabelCollection.remove(this.tempBackgroundLabel);
            this.tempBackgroundLabel = null;
        }
        if (this.tempForegroundLabel && this.labelCollection) {
            this.labelCollection.remove(this.tempForegroundLabel);
            this.tempForegroundLabel = null;
        }
    }

    /**
     * 更新临时图标位置
     */
    updateTempBillboardPosition(position) {
        if (this.tempBillboard) {
            this.tempBillboard.position = position;
        }
        if (this.tempBackgroundLabel) {
            this.tempBackgroundLabel.position = position;
        }
        if (this.tempForegroundLabel) {
            this.tempForegroundLabel.position = position;
        }
    }

    /**
     * 从鼠标位置获取地球坐标
     */
    getPositionFromMouse(mousePosition) {
        const ray = this.viewer.camera.getPickRay(mousePosition);
        if (!ray) return null;

        const position = this.viewer.scene.globe.pick(ray, this.viewer.scene);
        return position;
    }

    /**
     * 放置图标到指定位置
     */
    placeBillboard(position, options = {}) {
        if (!position) return;

        // 将笛卡尔坐标转换为经纬度
        const cartographic = Cesium.Cartographic.fromCartesian(position);
        const longitude = Cesium.Math.toDegrees(cartographic.longitude);
        const latitude = Cesium.Math.toDegrees(cartographic.latitude);
        const height = cartographic.height;

        // 创建图标数据
        const iconData = {
            longitude: longitude,
            latitude: latitude,
            height: height,
            color: options.color || '#FF5722',
            iconText: options.iconText || '📍',
            name: options.name || `自定义地点 ${this.iconCount + 1}`,
            ...options // 允许覆盖其他属性
        };

        // 添加图标
        this.addSingleBillboard(iconData);

        // 停止放置模式
        this.stopPlacementMode();

        // 调用回调函数
        if (this.placementCallback) {
            this.placementCallback(iconData, 'placed');
        }

        console.log(`图标已放置: ${iconData.name} (${longitude.toFixed(4)}, ${latitude.toFixed(4)})`);
        return iconData;
    }

    /**
     * 检查是否在放置模式中
     */
    isInPlacementMode() {
        return this.placementMode;
    }

    /**
     * 便捷方法：添加图标（自动判断是否使用放置模式）
     */
    addIcon(data, usePlacementModeIfNoCoords = true) {
        // 如果提供了坐标，直接添加
        if (data.longitude !== undefined && data.latitude !== undefined) {
            this.addSingleBillboard(data);
            return true;
        }

        // 如果没有提供坐标且允许使用放置模式
        if (usePlacementModeIfNoCoords) {
            this.startPlacementMode(data, (result, status) => {
                if (status === 'placed') {
                    console.log('图标放置成功:', result);
                } else {
                    console.log('图标放置已取消');
                }
            });
            return false; // 返回false表示进入放置模式
        }

        // 既不提供坐标也不使用放置模式
        console.error('未提供坐标且未启用放置模式');
        return false;
    }
}